import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, FormControl, Validators, AbstractControl } from '@angular/forms';
import { NzMessageService } from 'ng-zorro-antd';

// services
import { ConstantService } from '../../../../../core/services/constant.service';
import { ServerService } from '../../../../../core/services/server.service';
import { StorageService } from '../../../../../core/services/storage.service';

@Component({
    selector: 'app-menu-management',
    templateUrl: './menu-management.component.html',
    styleUrls: ['./menu-management.component.css']
})
export class MenuManagementComponent implements OnInit {
    isVisible: boolean = false; // 是否显示modal
    isConfirmLoading: boolean = false; // modal中点击保存的时候的过渡效果
    menuForm: FormGroup; // 菜单管理表单
    menuList: object[] = []; // 全部菜单
    upLevels: object[] = []; // 上级菜单数组
    _current: number = 1;
    _pageSize: number = 10;
    _total: number = 1;
    _loading: boolean = true;
    isViewStateUpdate: boolean = false;  // 页面是否是更新状态
    
    constructor(
        private fb: FormBuilder,
        private constant: ConstantService,
        private server: ServerService,
        private storage: StorageService,
        private message: NzMessageService
    ) {
        /**
         * 初始化菜单管理表单
         * 菜单等级: level
         * 菜单名称: name
         */
        this.menuForm = this.fb.group({
            _id: [''],
            level: ['1'],
            name: [null, Validators.required],
            upLevel: [''],
            url: ['', Validators.required],
            icon: ['', Validators.required],
            type: ['1', Validators.required]
        });
    }

    ngOnInit() {
        // 页面初始化加载全部菜单
        this.getAllMenus();
    }

    /**
     * 显示modal,添加或更新菜单信息
     * @param id 
     */
    async showModal(id) {
        this.isVisible = true;
        if (id) {
            this.isViewStateUpdate = true;
            // 如果id存在,则获取菜单详情
            const menuResult = await this.server.fetch(this.constant.api.manage.menu.findOne, { id });
            if (menuResult) {
                this.menuForm.controls['_id'].setValue(menuResult.data._id);
                this.menuForm.controls['name'].setValue(menuResult.data.name);
                this.menuForm.controls['level'].setValue(menuResult.data.level);
                this.menuForm.controls['url'].setValue(menuResult.data.url);
                this.menuForm.controls['icon'].setValue(menuResult.data.icon);
                this.menuForm.controls['type'].setValue(menuResult.data.type);
                if (menuResult.data.upLevel) {
                    await this.getMenus(Number(menuResult.data.level) - 1 + '');
                    if (menuResult.data.upLevel) {
                        this.menuForm.controls['upLevel'].setValue(menuResult.data.upLevel);
                    }
                }
            }
        } else {
            this.isViewStateUpdate = false;
            this.menuForm.controls['_id'].setValue('');
            this.menuForm.controls['level'].setValue('1');
            this.menuForm.controls['url'].setValue('');
            this.menuForm.controls['icon'].setValue('');
            this.menuForm.controls['type'].setValue('1');
        }
    }

    // 获取表单项
    getFormControl(name): AbstractControl {
        return this.menuForm.controls[name];
    }

    /**
     * 保存 || 更新
     * @param e 
     * @param menu 
     */
    async handleOk(e, menu): Promise<void> {
        this.isConfirmLoading = true;
        // 保存
        const result = await this.server.fetch(this.constant.api.manage.menu[this.isViewStateUpdate ? 'update' : 'save'], menu);
        if (result) {
            this.message.success('保存菜单成功');
            if (!this.isViewStateUpdate) {
                // 清空表单
                this.menuForm.reset();
                this.menuForm.controls['level'].setValue('1');
                this.menuForm.controls['type'].setValue('1');
            } else {
                this.isVisible = false;
            }
            this.isConfirmLoading = false;
            this.getAllMenus();
        } else {
            this.isConfirmLoading = false;
        }
    }

    /**
     * 关闭modal
     * @param e 
     */
    handleCancel(e): void {
        this.menuForm.controls['name'].setValue(null);
        this.isVisible = false;
    }

    /**
     * 菜单级别切换事件
     */
    async menuRadioChange(level: string): Promise<void> {
        this.menuForm.controls['level'].setValue(level);
        if (level !== '1') {
            await this.getMenus(Number(level) - 1 + '');
            this.menuForm.controls['upLevel'].setValue(this.upLevels.length > 0 ? this.upLevels[0]['_id'] : '');
        } else {
            this.menuForm.controls['upLevel'].setValue('');
        }
    }

    /**
     * 获取全部菜单列表
     */
    async getAllMenus(): Promise<void> {
        let param = {
            page: this._current,
            limit: this._pageSize
        };
        const allMenusResult = await this.server.fetch(this.constant.api.manage.menu.findAll, param);
        if (allMenusResult) {
            this.menuList = allMenusResult.data.data;
            this._total = allMenusResult.data.count;
            this._loading = false;
        }
    }

    /**
     * 获取菜单列表
     * @param level 
     */
    async getMenus(level: string): Promise<void> {
        let param = { level };
        const menusResult = await this.server.fetch(this.constant.api.manage.menu.find, param);
        if (menusResult) {
            this.upLevels = menusResult.data;
        }
    }

    /**
     * 删除菜单
     * @param id 
     */
    async del(id: string): Promise<void> {
        const delResult = await this.server.fetch(this.constant.api.manage.menu.del, { id });
        if (delResult) {
            this.message.success('删除成功');
            this.getAllMenus();
        }
    }

}
